package lion.framework.core.web;

import java.io.File;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import lion.dev.lang.Lang;
import lion.framework.core.ApplicationInitializer;
import lion.framework.core.task.AutoTaskManager;
import lion.framework.core.util.AppPaths;

/**
 * Web应用初始化类,扫描注解，初始化应用
 *
 * <pre>
 * time   2013 2013-4-24 上午11:32:53
 * mail   hl_0074@sina.com
 * </pre>
 *
 * @author lion
 */
@WebListener
public class WebApplicationListener implements ServletContextListener {

	private Log log = LogFactory.getLog(WebApplicationListener.class);

	@Override
	public void contextDestroyed(ServletContextEvent servletContextEvent) {

		AutoTaskManager.stop();
		ApplicationContext.setContext(null);
	}

	@Override
	public void contextInitialized(ServletContextEvent servletContextEvent) {

		ApplicationContext.setContext(servletContextEvent.getServletContext());

		if (log.isInfoEnabled()) {
			log.info("start initialized web application " + servletContextEvent.getServletContext().getContextPath());
		}
		long start = System.currentTimeMillis();

		// ApplicationContext.setContext(servletContextEvent.getServletContext());

		initWebPath(servletContextEvent.getServletContext());
		try {
			ApplicationInitializer.init();
		} catch (Exception e) {
			if (log.isErrorEnabled()) {
				log.error("application init error", e);
			}
		}

		if (log.isInfoEnabled()) {
			log.info("web application " + servletContextEvent.getServletContext().getContextPath() + " initialized in " + (System.currentTimeMillis() - start) + "ms");
		}
	}

	private void initWebPath(ServletContext context) {

		if (StringUtils.isBlank(AppPaths.WEBROOT)) {
			AppPaths.WEBROOT = context.getRealPath("/");
		}
		if (StringUtils.isBlank(AppPaths.TEMPDIR)) {
			AppPaths.TEMPDIR = Lang.nvl(((File) context.getAttribute("javax.servlet.context.tempdir")).getAbsolutePath(), System.getProperty("java.io.tmpdir"));
		}
		if (StringUtils.isBlank(AppPaths.WEBCONTEXT)) {
			AppPaths.WEBCONTEXT = context.getContextPath();
		}
		if (StringUtils.isBlank(AppPaths.WEBINF)) {
			AppPaths.WEBINF = context.getRealPath("/WEB-INF");
		}
		if (StringUtils.isBlank(AppPaths.LIBPATH)) {
			AppPaths.LIBPATH = AppPaths.WEBINF + "/lib";
		}
		if (StringUtils.isBlank(AppPaths.EXTDIR)) {
			AppPaths.EXTDIR = AppPaths.WEBINF + "/ext";
		}

	}
}
